import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo } from '@/api/user'
import { login } from '@/api/user'
import { constantRoutes } from '@/router'
import router from '@/router'

const state = {
  token: getToken(), // 从缓存中读取初始值
  userInfo: {}, // 存储用户基本资料状态
  routesSiderBar: constantRoutes, // 静态路由的数组
  routes: []
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  async login(context, data) {
    const result = await login(data)

    context.commit('setToken', result.data.token)
    await context.dispatch('getUserInfo')
  },
  // 获取用户的基本资料
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result.data.user)
  },
  // 退出登录的action
  logout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})

    router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
